const { staff_collection } = require('../config')
const { region_collection } = require('../config')
const { db } = require('../config')
const { command } = require('../config')
const _ = command
const department = require('../action/department');
// 分别计算与区域、区域中点距离的平均值的偏离值
exports.main = async (event, context) => {
    var regionArr = [];
    for (item of department.regions) {
        regionArr.push(item)
    }
    var i = 1;
    var staffSum = 0;
    for (region of regionArr) {
        console.log(regionArr.length, i, '开始更新区域：' + region)
        // 2.在obd信息表中查找到该员工账号的obd，获取所有obd的经纬度；无经obd则下一个
        const regionStaff = await db.collection(staff_collection).where({ region: region, status: _.neq('离职'), position: "全职装维" }).field({ name: true, toRegionCentersDistance: true }).limit(1000).get();
        var distanceSum = 0, staffArr = [];
        for (staff of regionStaff.data) {
            if (staff && staff.hasOwnProperty('toRegionCentersDistance')) {
                let item = { _id: staff._id, toRegionCentersDistance: staff.toRegionCentersDistance, name: staff.name };
                staffArr.push(item);
                distanceSum = distanceSum + staff.toRegionCentersDistance;
            }
        }
        staffSum += staffArr.length;
        var regionStaffCount = regionStaff.data.length;
        var regionDistanceAve = (distanceSum / staffSum).toFixed(2);
        console.log('装维离区域中心平均距离:', distanceSum, '/', staffSum, '=', regionDistanceAve);
        for (item of staffArr) {
            regionOffset = (item.toRegionCentersDistance - regionDistanceAve).toFixed(2);
            res = await db.collection(staff_collection).doc(item._id).update({
                regionOffset: regionOffset
            });
            console.log(i, '装维', item.name, '与区域平均距离偏离值:', item.toRegionCentersDistance, '-', regionDistanceAve, '=', regionOffset,res);
            i++;
        }
    }
    return '处理结束' + staffSum;
}